import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/weather_model.dart';
import '../services/weather_service.dart';
import '../services/theme_service.dart';
import '../services/favorites_service.dart';
import '../widgets/weather_card.dart';
import '../widgets/forecast_card.dart';
import '../widgets/theme_switch.dart';
import '../widgets/favorite_button.dart';
import 'detail_screen.dart';
import 'welcome_screen.dart';
import '../widgets/temperature_line_chart.dart';

class HomeScreen extends StatefulWidget {
  final String? initialCity;

  const HomeScreen({super.key, this.initialCity});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final TextEditingController _searchController = TextEditingController();
  CaiyunRealtime? _currentWeather;
  List<CaiyunDailyForecast> _dailyForecast = [];
  CaiyunLifeIndex? _lifeIndex;
  bool _isLoading = false;
  String _errorMessage = '';
  String _currentCity = '昆明';
  List<Map<String, dynamic>>? _hourlyWeather;
  bool _loadingHourly = false;
  String? _hourlyError;
  List<CustomWeatherReminder> _customReminders = [
    CustomWeatherReminder(condition: '温度高于', threshold: 35, enabled: true),
    CustomWeatherReminder(condition: '下雨', weatherType: '雨', enabled: true),
  ];

  @override
  void initState() {
    super.initState();
    // 如果传入了初始城市，使用它
    if (widget.initialCity != null) {
      _currentCity = widget.initialCity!;
    }
    _loadWeatherData();
    _fetchHourlyWeather();
  }

  Future<void> _loadWeatherData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });

    try {
      // 重新启用通过城市名称获取经纬度的逻辑
      List<double> coordinates =
          await WeatherService.getCoordinatesFromCity(_currentCity);
      double lon = coordinates[0];
      double lat = coordinates[1];

      final realtime = await WeatherService.getRealtimeWeather(lon, lat);
      final dailyData = await WeatherService.getDailyWeather(lon, lat);

      setState(() {
        _currentWeather = realtime;
        _dailyForecast = dailyData['forecast'];
        _lifeIndex = dailyData['lifeIndex'];
        _isLoading = false;
      });
      // 检查极端天气预警
      WeatherService.checkAndNotifyExtremeWeather(realtime);
      // 检查自定义提醒
      WeatherService.checkAndNotifyCustomReminders(realtime, _customReminders);
      _fetchHourlyWeather();
    } catch (e) {
      setState(() {
        _errorMessage = '加载天气数据失败: $e';
        _isLoading = false;
      });
    }
  }

  Future<void> _loadCurrentLocationWeather() async {
    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });

    try {
      final position = await WeatherService.getCurrentPosition();
      final city = await WeatherService.getCityFromCoordinates(
          position.longitude, position.latitude);

      final realtime = await WeatherService.getRealtimeWeather(
          position.longitude, position.latitude);
      final dailyData = await WeatherService.getDailyWeather(
          position.longitude, position.latitude);

      setState(() {
        _currentWeather = realtime;
        _dailyForecast = dailyData['forecast'];
        _lifeIndex = dailyData['lifeIndex'];
        _currentCity = city;
        _isLoading = false;
      });
    } on Exception catch (e) {
      setState(() {
        _errorMessage = '获取当前位置失败: $e';
        _isLoading = false;
      });
    }
  }

  Future<void> _searchCity() async {
    final city = _searchController.text.trim();
    if (city.isEmpty) return;

    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });

    try {
      // 重新启用通过城市名称获取经纬度的逻辑
      List<double> coordinates =
          await WeatherService.getCoordinatesFromCity(city);
      double lon = coordinates[0];
      double lat = coordinates[1];

      final realtime = await WeatherService.getRealtimeWeather(lon, lat);
      final dailyData = await WeatherService.getDailyWeather(lon, lat);

      setState(() {
        _currentWeather = realtime;
        _dailyForecast = dailyData['forecast'];
        _lifeIndex = dailyData['lifeIndex'];
        _currentCity = city; // 更新UI显示的城市名称
        _isLoading = false;
      });
      _fetchHourlyWeather();
      _searchController.clear();
    } catch (e) {
      setState(() {
        _errorMessage = '搜索城市失败: $e';
        _isLoading = false;
      });
    }
  }

  Future<void> _fetchHourlyWeather() async {
    setState(() {
      _loadingHourly = true;
      _hourlyError = null;
    });
    try {
      List<double> coordinates =
          await WeatherService.getCoordinatesFromCity(_currentCity);
      double lon = coordinates[0];
      double lat = coordinates[1];
      final data = await WeatherService.getHourlyWeather(lon, lat);
      setState(() {
        _hourlyWeather = data;
        _loadingHourly = false;
      });
    } catch (e) {
      setState(() {
        _hourlyError = e.toString();
        _loadingHourly = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeService = Provider.of<ThemeService>(context);
    final favoritesService = Provider.of<FavoritesService>(context);
    final isFavorite = favoritesService.isFavorite(_currentCity);

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Theme.of(context).brightness == Brightness.dark
                  ? const Color(0xFF1A1A1A)
                  : const Color(0xFF87CEEB),
              Theme.of(context).brightness == Brightness.dark
                  ? const Color(0xFF2D2D2D)
                  : const Color(0xFFB0E0E6),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部工具栏
              _buildTopBar(themeService, favoritesService, isFavorite),

              // 搜索栏
              _buildSearchBar(),

              // 错误信息
              if (_errorMessage.isNotEmpty) _buildErrorMessage(),

              // 主要内容
              Expanded(
                child:
                    _isLoading ? _buildLoadingIndicator() : _buildMainContent(),
              ),

              // 底部返回按钮
              _buildBottomNavigation(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTopBar(ThemeService themeService,
      FavoritesService favoritesService, bool isFavorite) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          IconButton(
            icon: Icon(
              themeService.themeMode == ThemeMode.dark
                  ? Icons.light_mode
                  : Icons.dark_mode,
              color: Colors.white,
            ),
            onPressed: () => themeService.toggleTheme(),
          ),
          IconButton(
            icon: const Icon(Icons.notifications, color: Colors.white),
            onPressed: _showReminderSettings,
          ),
          IconButton(
            icon: Icon(
              isFavorite ? Icons.favorite : Icons.favorite_border,
              color: isFavorite ? Colors.red : Colors.white,
            ),
            onPressed: () {
              if (isFavorite) {
                favoritesService.removeFavorite(_currentCity);
              } else {
                favoritesService.addFavorite(_currentCity);
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.9),
        borderRadius: BorderRadius.circular(25),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          const Icon(Icons.search, color: Colors.grey),
          const SizedBox(width: 12),
          Expanded(
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                hintText: '搜索城市...',
                border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
              ),
              onSubmitted: (_) => _searchCity(),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.location_on, color: Colors.blue),
            onPressed: _loadCurrentLocationWeather,
          ),
          const ThemeSwitch(),
        ],
      ),
    );
  }

  Widget _buildErrorMessage() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.red.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          const Icon(Icons.error, color: Colors.red, size: 20),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              _errorMessage,
              style: const TextStyle(color: Colors.red, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(color: Colors.white),
          SizedBox(height: 16),
          Text(
            '加载中...',
            style: TextStyle(color: Colors.white, fontSize: 16),
          ),
        ],
      ),
    );
  }

  Widget _buildMainContent() {
    if (_currentWeather == null) {
      return const Center(
        child: Text(
          '暂无天气数据',
          style: TextStyle(color: Colors.white, fontSize: 16),
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 当前天气卡片
          Stack(
            children: [
              WeatherCard(
                weather: _currentWeather!,
                city: _currentCity,
                onTap: () {
                  final isCurrentLocation = _currentCity == '当前位置';
                  Navigator.of(context).pushNamed(
                    '/detail',
                    arguments: {
                      'weather': _currentWeather!,
                      'city': isCurrentLocation ? '昆明' : _currentCity,
                      'lifeIndex': _lifeIndex,
                      'forecast': null,
                      'lon': null,
                      'lat': null,
                      'customReminders': _customReminders,
                    },
                  );
                },
              ),
              Positioned(
                top: 8,
                right: 8,
                child: FavoriteButton(city: _currentCity),
              ),
            ],
          ),

          const SizedBox(height: 24),

          // 3天天气预报标题
          const Text(
            '3天天气预报',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),

          const SizedBox(height: 16),

          // 3天天气预报卡片
          SizedBox(
            height: 120,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _dailyForecast.length,
              itemBuilder: (context, index) {
                return Padding(
                  padding: EdgeInsets.only(
                    right: index < _dailyForecast.length - 1 ? 12 : 0,
                  ),
                  child: ForecastCard(
                    forecast: _dailyForecast[index],
                    onTap: () {
                      final day = _dailyForecast[index];
                      Navigator.of(context).pushNamed(
                        '/detail',
                        arguments: {
                          'weather': _currentWeather!,
                          'city': _currentCity,
                          'lifeIndex': null,
                          'forecast': day,
                          'lon': null,
                          'lat': null,
                          'customReminders': _customReminders,
                        },
                      );
                    },
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomNavigation() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton.icon(
            onPressed: () {
              Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(
                  builder: (context) => const WelcomeScreen(),
                ),
                (route) => false,
              );
            },
            icon: const Icon(Icons.home, color: Colors.white),
            label: const Text(
              '返回首页',
              style: TextStyle(color: Colors.white),
            ),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue.withOpacity(0.8),
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _showReminderSettings() {
    showDialog(
      context: context,
      builder: (context) {
        double temp = _customReminders[0].threshold ?? 35;
        bool rain = _customReminders[1].enabled;
        return AlertDialog(
          title: const Text('天气提醒设置'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  const Text('高温提醒(>'),
                  SizedBox(
                    width: 40,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      controller: TextEditingController(text: temp.toString()),
                      onChanged: (v) {
                        temp = double.tryParse(v) ?? 35;
                      },
                    ),
                  ),
                  const Text('°C)'),
                  Checkbox(
                    value: _customReminders[0].enabled,
                    onChanged: (v) {
                      setState(() {
                        _customReminders[0] = CustomWeatherReminder(
                          condition: '温度高于',
                          threshold: temp,
                          enabled: v ?? true,
                        );
                      });
                    },
                  ),
                ],
              ),
              Row(
                children: [
                  const Text('下雨提醒'),
                  Checkbox(
                    value: rain,
                    onChanged: (v) {
                      setState(() {
                        _customReminders[1] = CustomWeatherReminder(
                          condition: '下雨',
                          weatherType: '雨',
                          enabled: v ?? true,
                        );
                      });
                    },
                  ),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                setState(() {
                  _customReminders[0] = CustomWeatherReminder(
                    condition: '温度高于',
                    threshold: temp,
                    enabled: _customReminders[0].enabled,
                  );
                  _customReminders[1] = CustomWeatherReminder(
                    condition: '下雨',
                    weatherType: '雨',
                    enabled: rain,
                  );
                });
                Navigator.of(context).pop();
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
}
